<template>
  <div class="app-container">
     <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
        <el-form-item label="优惠券名称" prop="name">
           <el-input
              v-model="queryParams.name"
              placeholder="请输入优惠券名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
           />
        </el-form-item>
        <!-- <el-form-item label="优惠券名称" prop="postName">
           <el-input
              v-model="queryParams.postName"
              placeholder="请输入优惠券名称"
              clearable
              style="width: 200px"
              @keyup.enter="handleQuery"
           />
        </el-form-item>
        <el-form-item label="状态" prop="status">
           <el-select v-model="queryParams.status" placeholder="优惠券状态" clearable style="width: 200px">
              <el-option
                 v-for="dict in sys_normal_disable"
                 :key="dict.value"
                 :label="dict.label"
                 :value="dict.value"
              />
           </el-select>
        </el-form-item> -->
        <el-form-item>
           <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
           <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
     </el-form>

     <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
           <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAdd"
              v-hasPermi="['coupon:index:add']"
           >新增</el-button>
        </el-col>
        <!-- <el-col :span="1.5">
           <el-button
              type="success"
              plain
              icon="Edit"
              :disabled="single"
              @click="handleUpdate"
              v-hasPermi="['system:post:edit']"
           >修改</el-button>
        </el-col>
        <el-col :span="1.5">
           <el-button
              type="danger"
              plain
              icon="Delete"
              :disabled="multiple"
              @click="handleDelete"
              v-hasPermi="['system:post:remove']"
           >删除</el-button>
        </el-col> -->
        <!-- <el-col :span="1.5">
           <el-button
              type="warning"
              plain
              icon="Download"
              @click="handleExport"
              v-hasPermi="['coupon:index:export']"
           >导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar> -->
     </el-row>

     <el-table v-loading="loading" :data="couponList" @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="优惠券名称" align="left" prop="name"   :show-overflow-tooltip="true"/>
        <el-table-column label="优惠券类型" align="center" prop="createTime" width="200" :show-overflow-tooltip="true">
        <template #default="scope">
          <span>{{ scope.row.couponType==10?'满减券':'折扣券' }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="最低消费金额(元)"
        align="center"
        prop="minPrice"
        :show-overflow-tooltip="true"
        width="130"
      />
      <el-table-column label="有效时间" align="center" prop="createTime" width="200">
        <template #default="scope">
          <span v-if="scope.row.startTime">{{ parseTime(scope.row.startTime,'{y}-{m}-{d}') }} ~ {{ parseTime( scope.row.endTime,'{y}-{m}-{d}') }}</span>
          <span v-else>{{ scope.row.expireDay }}天</span>
        </template>
      </el-table-column>
      <el-table-column label="数量" align="center" prop="createTime" width="120">
        <template #default="scope">
          <span>{{ scope.row.totalNum == -1?'不限': scope.row.totalNum}}</span>
        </template>
      </el-table-column>
        <el-table-column label="排序" align="center" prop="sort" />
        <el-table-column label="状态" align="center" prop="status">
           <template #default="scope">
              <dict-tag :options="stateObjects" :value="scope.row.status+''" />
           </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
           <template #default="scope">
              <span>{{ parseTime(scope.row.createTime) }}</span>
           </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" class-name="small-padding fixed-width">
           <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['coupon:index:edit']">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['coupon:index:remove']">删除</el-button>
           </template>
        </el-table-column>
     </el-table>

     <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
     />

     <!-- 添加或修改优惠券对话框 -->
     <el-dialog :title="title" v-model="open" width="800px" append-to-body>
        <div class="form_box">
          <el-form ref="couponsRef" :model="form" :rules="rules" label-width="130px">
            <el-row>
            <el-col :span="12">
              <el-form-item label="优惠券名称" prop="name" >
                <el-input v-model="form.name" placeholder="请输入优惠券名称" style="width:230px"/>
              </el-form-item>
            </el-col>
            <el-col :span="12" >
              <el-form-item label="最低消费金额(元)" prop="minPrice">
                <el-input-number v-model="form.minPrice" controls-position="right" :min="0"  style="width:230px"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="优惠券类型" prop="couponType">
                <el-select
                    v-model="form.couponType"
                    placeholder="请选择优惠券类型"
                    @change="couponTypeChange"
                    style="width:230px"
                  >
                    <el-option
                      v-for="dict in classifyOptions"
                      :key="dict.value"
                      :label="dict.name"
                      :value="dict.value"
                    />
                  </el-select>
                <!-- <treeselect v-model="form.categoryId" :options="classifyOptions" :normalizer="normalizer" placeholder="请选择优惠券分类" /> -->
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.couponType == 10">
              <el-form-item label="减免金额(元)" prop="reducePrice">
                <el-input-number v-model="form.reducePrice" controls-position="right" :min="0" style="width:230px"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.couponType == 20">
              <el-form-item label="折扣率(0~100%)" prop="discount">
                <el-input-number v-model="form.discount" controls-position="right" :min="0" :max="100" style="width:230px"></el-input-number>
              </el-form-item>
            </el-col>

            <el-col :span="12" >
              <el-form-item label="到期类型" prop="expireType">
                <el-select
                    v-model="form.expireType"
                    placeholder="请选择到期类型"
                    @change="expireTypeChange"
                    style="width:230px"
                  >
                    <el-option
                      v-for="dict in timeOptions"
                      :key="dict.value"
                      :label="dict.name"
                      :value="dict.value"
                    />
                  </el-select>
                <!-- <treeselect v-model="form.categoryId" :options="classifyOptions" :normalizer="normalizer" placeholder="请选择优惠券分类" /> -->
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.expireType == 10">
              <el-form-item label="有效期（天）" prop="expireDay">
                <el-input-number v-model="form.expireDay" controls-position="right" :min="0" style="width:230px"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="form.expireType == 20">
              <el-form-item label="固定时间" prop="dateRange">
                <el-date-picker
                  v-model="dateRange"
                  style="width:230px"

                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12" >
              <el-form-item label="数量(-1为不限)" prop="totalNum">
                <el-input-number v-model="form.totalNum" controls-position="right" style="width:230px"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排序" prop="sort">
                <el-input-number v-model="form.sort" controls-position="right" :min="0" style="width:230px"></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="状态" prop="status">
                  <el-radio-group v-model="form.status">
                    <el-radio
                      v-for="dict in stateObject"
                      :key="dict.value"
                      :label="dict.value"
                    >{{dict.label}}</el-radio>
                </el-radio-group>
              </el-form-item>

              </el-col>
          </el-row>
        </el-form>
        </div>

        <template #footer>
           <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
           </div>
        </template>
     </el-dialog>
  </div>
</template>

<script setup name="couponManage">
import { getCouponsList , addCoupons, editCoupons ,getCouponsDetail,delCoupons} from "@/api/coupons/coupons";
const { proxy } = getCurrentInstance();
const { goods_status } = proxy.useDict("goods_status");


const timeOptions = [
      {
        name:'领取后生效',
        value:10
      },{
        name:'固定时间',
        value:20
      }
];
const classifyOptions=[
  {
    name:'满减券',
    value:10
  },{
    name:'折扣券',
    value:20
  }
];
const stateObject = [
  {
    label:'正常',
    value:0
  },
  {
    label:'停用',
    value:1
  }
];

const stateObjects = [
  {
    elTagClass: "",
    elTagType: "success",
    label :"正常",
    value: "0"
  },
  {
    elTagClass: "",
    elTagType: "danger",
    label :"停用",
    value: "1"
  }
];


const couponList = ref([]);
const skuList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange =  ref('');
const data = reactive({
 form: {},
 queryParams: {
   pageNum: 1,
   pageSize: 10,
   name: undefined,
   status: undefined
 },
 rules: {
    name: [
      { required: true, message: "优惠券名称不能为空", trigger: "blur" }
    ],

    couponType: [
      { required: true, message: "优惠券类型不能为空", trigger: ["blur","change"] }
    ],

    sort:[
      { required: true, message: "优惠券排序不能为空", trigger: "change" }
    ],
 }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询优惠券列表 */
function getList() {
 loading.value = true;
 getCouponsList(queryParams.value).then(response => {
   couponList.value = response.rows;
   total.value = response.total;
   loading.value = false;
 });
}
/** 取消按钮 */
function cancel() {
 open.value = false;
 reset();
}
/** 表单重置 */
function reset() {

 form.value = {
    id: undefined,
    name: undefined,
    couponType: 10,
    reducePrice: undefined,
    discount: undefined,
    sort: undefined,
    minPrice: undefined,
    expireType: 10,
    startTime: undefined,
    endTime: undefined,
    totalNum: undefined,
    status:0
 };
 proxy.resetForm("couponsRef");
}
/** 搜索按钮操作 */
function handleQuery() {
 queryParams.value.pageNum = 1;
 getList();
}
/** 重置按钮操作 */
function resetQuery() {
 proxy.resetForm("queryRef");
 handleQuery();
}
/** 多选框选中数据 */
function handleSelectionChange(selection) {
 ids.value = selection.map(item => item.postId);
 single.value = selection.length != 1;
 multiple.value = !selection.length;
}
/** 新增按钮操作 */
function handleAdd() {
 reset();
 skuList.value = [];
 open.value = true;
 title.value = "添加优惠券";
}
/** 修改按钮操作 */
function handleUpdate(row) {
 reset();
 const id =  row.id;
 getCouponsDetail(id).then(response => {
    if(response.data.startTime && response.data.startTime!='0'){
      dateRange.value = [ proxy.parseTime( response.data.startTime,'{y}-{m}-{d}'), proxy.parseTime( response.data.endTime,'{y}-{m}-{d}')];
    }
   form.value = response.data;
   title.value = "修改优惠券";
   skuList.value = response.data.skuList;
   open.value = true;

 });
}
/** 提交按钮 */
function submitForm() {
 proxy.$refs["couponsRef"].validate(valid => {
   if (valid) {

    form.value.startTime = dateRange.value[0]
    form.value.endTime = dateRange.value[1]

     if (form.value.id != undefined) {
      editCoupons(form.value).then(response => {
         proxy.$modal.msgSuccess("修改成功");
         open.value = false;
         getList();
       });
     } else {
      addCoupons(form.value).then(response => {
         proxy.$modal.msgSuccess("新增成功");
         open.value = false;
         getList();
       });
     }
   }
 });
}
/** 删除按钮操作 */
function handleDelete(row) {
 const id = row.id;
 proxy.$modal.confirm('是否确认删除名称为"' + row.name + '"的数据项？').then(function() {
   return delCoupons(id);
 }).then(() => {
   getList();
   proxy.$modal.msgSuccess("删除成功");
 }).catch(() => {});
}
/** 导出按钮操作 */
function handleExport() {
 proxy.download("system/post/export", {
   ...queryParams.value
 }, `post_${new Date().getTime()}.xlsx`);
}
/** 时间选择 */
function couponTypeChange(e){
  if(e == 20){
    form.value.reducePrice = undefined
  }else{
    form.value.discount = undefined
  }
}
function expireTypeChange(e){

  if(e == 20){
    form.value.expireDay = undefined
  }else{
    dateRange.value = ''
    form.value.startTime = undefined
    form.value.endTimeTime = undefined
  }
}


getList();
</script>
<style lang="scss" scoped>
.form_box {

  overflow: auto;
  box-sizing: border-box;
  padding: 20px;
}
</style>
